# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 17:53:14 2021

@author: xuzhihan
"""

import datetime
import random
import os
import sys
import xlrd
import getpass

def cur_file_dir():
    try:
    # 获取脚本路径
         path = sys.path[0]

    # 判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
         if os.path.isdir(path):
             return path
         elif os.path.isfile(path):
             return os.path.dirname(path)
    except Exception as e:
             QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")
filepath =cur_file_dir()

def getbooklet():
    try:
        sheetlist = []
        for i in range(1,31):
            sheetlist.append("Unit"+str(i))
        testlist=getcte(sheetlist)
        testlist.sort(key=lambda x: x[0])
        return testlist
    except Exception as e:
        QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")

def getetc(sheetlist):
    try:
        readbook = xlrd.open_workbook(filepath+"\\booklet.xls")
        def getetclist(sheetlist):
            try:
                if not sheetlist:
                    return 0
                testlist = []
                for s in sheetlist:
                    sheet = readbook.sheet_by_name(s)
                    Flag = 1
                    for i in range(sheet.nrows):
                                sentences = ""
                                for w in sheet.row(i):
                                    if Flag == 1:
                                        Flag = 0
                                        continue
                                    w = str(w)
                                    if w == "empty:''":
                                        Flag = 1
                                        break
                                    else:
                                        sentences +="；"+ "".join(w[6:len(w)-1])
                                w= random.randint(1,sheet.ncols-1)
                                word = str(sheet.row(i)[0])
                                word = word[6:len(word)-1]

                                sentence =str(sheet.row(i)[w])
                                sentence = sentence[6:len(sentence)-1]
                                if sentence == "'":
                                    sentence = str(sheet.row(i)[1])
                                    sentence = sentence[6:len(sentence)-1]

                                testlist.append((word,sentence,sentences[1:]))
                return testlist
            except Exception as e:
                QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")
        testlist = getetclist(sheetlist)
        if testlist == 0:
            return 0
        random.shuffle(testlist)
        return testlist
    except Exception as e:
        QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")

def getcte(sheetlist):
    try:
        readbook = xlrd.open_workbook(filepath+"\\booklet.xls")
        def getctelist(sheetlist):
            try:
                if not sheetlist:
                    return 0
                testlist = []
                for s in sheetlist:
                    sheet = readbook.sheet_by_name(s)
                    word = ""
                    sentence = ""
                    Flag = 1
                    for i in range(sheet.nrows):
                        for w in sheet.row(i):
                            w = str(w)
                            if Flag == 1:
                                word = w[6:len(w)-1]
                                Flag = 0
                                continue
                            if w == "empty:''":
                                testlist.append((word,sentence[1:]))
                                word = ""
                                sentence = ""
                                Flag = 1
                                break
                            else:
                                sentence +="；"+ "".join(w[6:len(w)-1])
                return testlist
            except Exception as e:
                QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")


        testlist = getctelist(sheetlist)
        if testlist == 0:
            return 0
        random.shuffle(testlist)
        return testlist
    except Exception as e:
        QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")

def getfile():
    try:
        filepath = "C:\\users\\"+getpass.getuser()+"\\AppData\\Local"
        if not os.path.exists(filepath+"\\recobook"):
            return 0
        qianzhui = ""
        maxi = 0
        for root,dirs,files in os.walk(filepath+"\\recobook"):
            for dirc in dirs:
                if int(dirc) > maxi:
                    maxi = int(dirc)
                    qianzhui = dirc
        for root,dirs,files in os.walk(filepath+"\\recobook\\"+qianzhui):
            file = open(filepath+"\\recobook\\"+qianzhui+"\\"+files[0],"r")
            r = file.readlines()
        testlist = []
        for i in r:
            testlist.append((i[:i.index("%")],i[i.index("%")+1:len(i)-1]))
        return testlist
    except Exception as e:
        QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")

def savefile(reslist):
    try:
        filepath = "C:\\users\\"+getpass.getuser()+"\\AppData\\Local"
        houzhui = datetime.datetime.now().strftime('%m%d%H%M')
        if not os.path.exists(filepath+"\\recobook"):
            os.mkdir(filepath+"\\recobook")
        if not os.path.exists(filepath+"\\recobook\\"+houzhui):
            os.mkdir(filepath+"\\recobook\\"+houzhui)
        chengji = filepath+"\\recobook\\"+houzhui+"\\recobook"+str(len(reslist))+".txt"
        for r in reslist:
                with open(chengji, "a") as f:
                    f.write(r[0]+"%"+r[1]+"\n")
    except Exception as e:
                        QMessageBox.warning(self,"出错了","[错误提示(请联系开发人员处理)]：\n" + str(e)+"\n或识别失败导致")

